function jsUpload(id,maxsize,callback=false,updata={}) {
    var fileDir = "uploads";
    var images = $("#upload_"+id).val();
    $("#upload_"+id+"_text").text("上传中");
    var $file = event.currentTarget;
    var origin_type = $file.files[0].type;
    var file = $file.files;
    if ($.inArray(origin_type,["image/png","image/gif","image/jpeg","image/webp"]) < 0) {
        mviewToastr("error","当前不支持上传此类型图片,请上传JPG/PNG/GIF图片!");
        $("#upload_"+id).val('');
        $("#upload_"+id+"_text").text("上传");
        return;
    }
    $("#upload_"+id+"_text").text("压缩中");
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function (e) {
        var data = e.target.result;
        //加载图片获取图片真实宽度和高度
        var image = new Image();
        image.src = data;
        // 图片先加载完，才可以得到图片宽度和高度
        image.onload = function(){
            var width = image.width;
            var height = image.height;
            var pressParamas = {};
            if (width > 800) {
                pressParamas.width = 800;
            }
            if (file[0].size >= 1000000) {
                pressParamas.size = 300;
                pressParamas.quality = 0.8;
            } else if (file[0].size >= 500000) {
                pressParamas.size = 200;
                pressParamas.quality = 0.8;
            } else {
                pressParamas.size = 100;
                pressParamas.quality = 0.8;
            }
            if ($.inArray(origin_type,["image/png","image/webp"]) < 0) {
                pressParamas.type = file[0].type;
            } else {
                pressParamas.type = "image/jpeg";
            }
            imageConversion.compress($file.files[0],pressParamas).then(pressResult=>{
                // var pressImageUrl = URL.createObjectURL(pressResult);
                // $("#"+id+"_show").attr("src",pressImageUrl).show();
                var pressFile = blobToFile(pressResult,file[0].name,file[0].type);
                var oldSize = (file[0].size/1024).toFixed(0);
                var resultSize = (pressFile.size/1024).toFixed(0);
                if (resultSize > maxsize) {
                    mviewToastr("error","图片压缩后不能超过"+maxsize+"KB,当前为"+resultSize+"KB。");
                    $("#upload_"+id).val('');
                    $("#upload_"+id+"_text").text("上传");
                    return;
                }
                aliOssUpload(id,pressFile,fileDir,callback,"single",updata);
            });
        }
    }
}

function beianUpload(id,maxsize,callback=false,updata={}) {
    var fileDir = "uploads";
    var images = $("#upload_"+id).val();
    $("#upload_"+id+"_text").text("上传中");
    var $file = event.currentTarget;
    var origin_type = $file.files[0].type;
    var file = $file.files;
    if ($.inArray(origin_type,["image/png","image/gif","image/jpeg","image/webp"]) < 0) {
        mviewToastr("error","当前不支持上传此类型图片,请上传JPG/PNG/GIF图片!");
        $("#upload_"+id).val('');
        $("#upload_"+id+"_text").text("上传");
        return;
    }
    $("#upload_"+id+"_text").text("压缩中");
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function (e) {
        var data = e.target.result;
        //加载图片获取图片真实宽度和高度
        var image = new Image();
        image.src = data;
        // 图片先加载完，才可以得到图片宽度和高度
        image.onload = function(){
            var width = image.width;
            var height = image.height;
            var pressParamas = {};
            if (width > height) {
                // 正面
                // if (width <= 1280) {
                //     mviewToastr("error","照片宽度不能低于1280px。");
                //     return;
                // }
                if (height < 500) {
                    mviewToastr("error","照片高度不能低于500px。");
                    return;
                }
            } else {
                // 竖面
                if (width < 500) {
                    mviewToastr("error","照片宽度不能低于500px。");
                    return;
                }
                // if (height <= 1280) {
                //     mviewToastr("error","照片高度不能低于1280px。");
                //     return;
                // }
            }
            if ($.inArray(origin_type,["image/png","image/webp"]) < 0) {
                pressParamas.type = file[0].type;
            } else {
                pressParamas.type = "image/jpeg";
            }
            imageConversion.compress($file.files[0],pressParamas).then(pressResult=>{
                // var pressImageUrl = URL.createObjectURL(pressResult);
                // $("#"+id+"_show").attr("src",pressImageUrl).show();
                var pressFile = blobToFile(pressResult,file[0].name,file[0].type);
                var oldSize = (file[0].size/1024).toFixed(0);
                var resultSize = (pressFile.size/1024).toFixed(0);
                if (resultSize > maxsize) {
                    mviewToastr("error","图片压缩后不能超过"+maxsize+"KB,当前为"+resultSize+"KB。");
                    $("#upload_"+id).val('');
                    $("#upload_"+id+"_text").text("上传");
                    return;
                }
                aliOssUpload(id,pressFile,fileDir,callback,"single",updata);
            });
        }
    }
}

function fixWidthUpload(id,width,height,size,quality,callback=false,updata={}) {
    var fileDir = "uploads";
    var images = $("#upload_"+id).val();
    $("#upload_"+id+"_text").text("上传中");
    var $file = event.currentTarget;
    var origin_type = $file.files[0].type;
    var file = $file.files;
    if ($.inArray(origin_type,["image/png","image/gif","image/jpeg","image/webp"]) < 0) {
        mviewToastr("error","当前不支持上传此类型图片,请上传JPG/PNG/GIF图片!");
        $("#upload_"+id).val('');
        $("#upload_"+id+"_text").text("上传");
        return;
    }
    $("#upload_"+id+"_text").text("压缩中");
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function (e) {
        var data = e.target.result;
        //加载图片获取图片真实宽度和高度
        var image = new Image();
        image.src = data;
        // 图片先加载完，才可以得到图片宽度和高度
        image.onload = function(){
            var pressParamas = {};
            pressParamas.width = width;
            pressParamas.height = height;
            pressParamas.size = size;
            pressParamas.quality = quality;
            console.log(pressParamas);
            if ($.inArray(origin_type,["image/png","image/webp"]) < 0) {
                pressParamas.type = file[0].type;
            } else {
                pressParamas.type = "image/jpeg";
            }
            imageConversion.compress($file.files[0],pressParamas).then(pressResult=>{
                var pressFile = blobToFile(pressResult,file[0].name,file[0].type);
                aliOssUpload(id,pressFile,fileDir,callback,"single",updata);
            });
        }
    }
}

function jsUploadMore(id,maxsize,callback=false,updata) {
    var fileDir = "uploads";
    var images = $("#upload_"+id).val();
    $("#upload_"+id+"_text").text("上传中");
    var $file = event.currentTarget;
    var origin_type = $file.files[0].type;
    var file = $file.files;
    if ($.inArray(origin_type,["image/png","image/gif","image/jpeg","image/webp"]) < 0) {
        mviewToastr("error","当前不支持上传此类型图片,请上传JPG/PNG/GIF图片!");
        $("#upload_"+id).val('');
        $("#upload_"+id+"_text").text("上传");
        return;
    }
    $("#upload_"+id+"_text").text("压缩中");
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function (e) {
        var data = e.target.result;
        //加载图片获取图片真实宽度和高度
        var image = new Image();
        image.src = data;
        // 图片先加载完，才可以得到图片宽度和高度
        image.onload = function(){
            var width = image.width;
            var height = image.height;
            var pressParamas = {};
            if (width > 800) {
                pressParamas.width = 800;
            }
            if (file[0].size >= 1000000) {
                pressParamas.size = 300;
                pressParamas.quality = 0.8;
            } else if (file[0].size >= 500000) {
                pressParamas.size = 200;
                pressParamas.quality = 0.8;
            } else {
                pressParamas.size = 100;
                pressParamas.quality = 0.8;
            }
            if ($.inArray(origin_type,["image/png","image/webp"]) < 0) {
                pressParamas.type = file[0].type;
            } else {
                pressParamas.type = "image/jpeg";
            }
            imageConversion.compress($file.files[0],pressParamas).then(pressResult=>{
                // var pressImageUrl = URL.createObjectURL(pressResult);
                // $("#"+id+"_show").attr("src",pressImageUrl).show();
                var pressFile = blobToFile(pressResult,file[0].name,file[0].type);
                var oldSize = (file[0].size/1024).toFixed(0);
                var resultSize = (pressFile.size/1024).toFixed(0);
                if (resultSize > maxsize) {
                    mviewToastr("error","图片压缩后不能超过"+maxsize+"KB,当前为"+resultSize+"KB。");
                    $("#upload_"+id).val('');
                    $("#upload_"+id+"_text").text("上传");
                    return;
                }
                aliOssUpload(id,pressFile,fileDir,callback,"list",updata);
            });
        }
    }
}

function uploadMoreImage(id,maxsize,callback=false,updata) {
    var fileDir = "uploads";
    var images = $("#upload_"+id).val();
    $("#upload_"+id+"_text").text("上传中");
    var $file = event.currentTarget;
    var origin_type = $file.files[0].type;
    var file = $file.files;
    if ($.inArray(origin_type,["image/png","image/gif","image/jpeg","image/webp"]) < 0) {
        mviewToastr("error","当前不支持上传此类型图片,请上传JPG/PNG/GIF图片!");
        $("#upload_"+id).val('');
        $("#upload_"+id+"_text").text("上传");
        return;
    }
    $("#upload_"+id+"_text").text("压缩中");
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function (e) {
        var data = e.target.result;
        //加载图片获取图片真实宽度和高度
        var image = new Image();
        image.src = data;
        // 图片先加载完，才可以得到图片宽度和高度
        image.onload = function(){
            var width = image.width;
            var height = image.height;
            var pressParamas = {};
            if (width > 800) {
                pressParamas.width = 800;
            }
            if (file[0].size >= 1000000) {
                pressParamas.size = 300;
                pressParamas.quality = 0.8;
            } else if (file[0].size >= 500000) {
                pressParamas.size = 200;
                pressParamas.quality = 0.8;
            } else {
                pressParamas.size = 100;
                pressParamas.quality = 0.8;
            }
            if ($.inArray(origin_type,["image/png","image/webp"]) < 0) {
                pressParamas.type = file[0].type;
            } else {
                pressParamas.type = "image/jpeg";
            }
            imageConversion.compress($file.files[0],pressParamas).then(pressResult=>{
                // var pressImageUrl = URL.createObjectURL(pressResult);
                // $("#"+id+"_show").attr("src",pressImageUrl).show();
                var pressFile = blobToFile(pressResult,file[0].name,file[0].type);
                var oldSize = (file[0].size/1024).toFixed(0);
                var resultSize = (pressFile.size/1024).toFixed(0);
                if (resultSize > maxsize) {
                    mviewToastr("error","图片压缩后不能超过"+maxsize+"KB,当前为"+resultSize+"KB。");
                    $("#upload_"+id).val('');
                    $("#upload_"+id+"_text").text("上传");
                    return;
                }
                aliOssUpload(id,pressFile,fileDir,callback,"list",updata);
            });
        }
    }
}

function blobToFile(blob,name,type) {
    return new window.File([blob],name,{"type":type});
}

function aliOssUpload(id,file,dir,callback,type,updata){
    $("#upload_"+id+"_text").text("上传中");
    var randomId = generateRandomInteger(10000,99999);
    //获取上传的文件名，并得到文件后缀
    if (type == "editor") {
        var point = file.name.lastIndexOf(".");//获取文件后缀
        var file_type = file.name.substr(point);
    } else {
        var fileInput=$("#upload_"+id).val();
        var point = fileInput.lastIndexOf(".");
        var file_type = fileInput.substr(point);//获取文件后缀
    }
    var day = getCurrentTime("day");
    var time = getCurrentTime("time");
    var imageName = randomId+file_type;
    var file_name = dir+"/"+day+"/"+time+randomId+file_type;
    //发送ajax请求我方php后端获取上传OSS时必要的参数信息
    $.ajax({
        type : "get", //提交方式
        url : "/api/version/1/oss/alioss_access_token",//路径
        data : {
            "dir" : dir
        },//数据，这里使用的是Json格式进行传输
        success : function(res) {//返回数据根据结果进行相应的处理
            res = JSON.parse(res);
            var imageurl = res.host+file_name;
            //上返回的参数使用formData中
            let formData = new FormData();
            formData.append('key', file_name);
            formData.append('OSSAccessKeyId', res.accessid);
            formData.append('policy', res.policy);
            formData.append('Signature', res.signature);
            formData.append('callback', res.callback);
            formData.append('success_action_status', 200); // 成功后返回的操作码
            formData.append('file', file);
            //接收到服务端返回的签名参数，开始通过另一个Ajax请求来上传文件到OSS
            //成功获取签名后上传文件到阿里云OSS
            $.ajax({
                type : "POST", //提交方式
                url : res.host,//路径
                dataType:'JSON',
                processData: false,
                cache: false,
                async: false,
                contentType: false,
                data : formData,
                success : function(result) {
                    if (result.Status == "Ok") {
                        if (type == "single") {
                            aliOssUploadBack(id,imageurl,callback,imageName,updata);
                        } else if(type == "editor") {
                            aliOssUploadEditorBack(id,imageurl,callback,imageName,updata);
                        } else {
                            aliOssListsUploadBack(id,imageurl,callback,imageName,updata);
                        }
                    }
                },error:function(err){
                    $("#upload_"+id+"_text").text("上传");
                    mviewToastr("error","图片上传失败,请联系客服处理！");
                }
            });
        },error:function(err){
            $("#upload_"+id+"_text").text("上传");
            mviewToastr("error","网络异常,请联系客服处理！");
        }
    });
}

function generateRandomInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getCurrentTime(type){
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    if (type == "day") {
        return year+month+day;
    } else {
        return hour+minutes+seconds;
    }
}

function aliOssUploadBack(id,imageurl,callback,imageName,updata) {
    $("#"+id+"_show").attr("src",imageurl).show();
    $("#"+id).val(imageurl);
    // 清空上传选择
    $("#upload_"+id).val('');
    $("#upload_"+id+"_text").text("上传");
    $("#"+id).trigger('change');
    if (callback) {
        jsUploadCallBack(id,imageurl,imageName,updata,"");
    }
}

function aliOssListsUploadBack(id,imageurl,callback,imageName,updata) {
    var imageid = Math.ceil(Math.random()*10000000);
    $("#"+id+"_lists").prepend('<div id="'+imageid+'"><img src="'+imageurl+'" class="m-file-image"><i class="m-file-del bx bx-x" onclick=\'deleteImages("'+id+'","'+imageurl+'","'+imageid+'");\'></i></div>');
    var imageLists = JSON.parse($("#"+id).val());
    imageLists.push(imageurl);
    $("#"+id).val(JSON.stringify(imageLists));
    // 清空上传选择
    $("#upload_"+id).val('');
    $("#upload_"+id+"_text").text("上传");
    $("#"+id).trigger('change');
    if (callback) {
        jsUploadCallBack(id,imageurl,imageName,updata,imageid);
    }
}

function aliOssUploadEditorBack(id,imageurl,callback,imageName,updata) {
    wangEditorUploadBack(imageurl);
}

function deleteImages(id,image,imageid) {
    $("#"+imageid).remove();
    var images = JSON.parse($("#"+id).val());
    var imageLists = [];
    $.each(images,function(idx,fimage){
        if (fimage != image) {
            imageLists.push(fimage);
        }
    });
    $("#"+id).val(JSON.stringify(imageLists));
    jsImagesListsDeleteCallback(id,image,imageid);
}

function getScaleSize(that,rst){
    var sourceSize = (that.files[0].size/1024).toFixed(2);
    var resultSize = (rst.fileLen/1024).toFixed(2);
    var scale = parseInt(100 - (resultSize / sourceSize * 100));
    console.log("源文件:"+sourceSize+"KB\r\n压缩后:"+resultSize+"KB\r\n节省:"+scale+"%");
}
